/*
 * @Author: your name
 * @Date: 2021-06-24 00:30:57
 * @LastEditTime: 2022-03-19 14:55:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /shujucaiji/lib/handler/project.js
 */
const { Project } = require('../db');
const superagent = require('superagent');

// const mock1 = require('../mock/data1');

// const writeMock = () => {};

// // 写入数据

// writeMock.getProjectInfo = async (data) => {
//   const {projectName, projectId } = data;

//   //   const {vehId } = require('../mock/data2');
//   // 查询项目id是否存在
//   let project = await Project.findOne({ projectId });
//   if(!project) {
//     project = new Project({
//       projectName,
//       projectId,
//     });
//   } else {
//     project.projectName = projectName;
//   }

//   project.save();
// };

// writeMock.getProjectInfo(mock1[0]);
const outer = () => {};

// 项目列表查询
outer.getProjectList = async () => {
  const list = await Project.find({});
  if(!list) {
    return { 'success': false, 'msg': '查询失败' };
  } else {
    return { 'success': true, 'msg': '项目信息查询成功', data: list};
  }
};

// 添加项目信息
outer.createProjectInfo = async (params) => {
  const {
    // projectName, projectId, address
    projectName,
    code,
    location,
    sequence,
    operator,
    len,
    total,
    innerRadius,
    outerRadius,
    geology,
  } = params;
  // 项目是否已经存在
  let project = await Project.findOne({ 'projectId': code }).catch(err => console.log(err, '-----'));
  console.log(project, 'project');
  if(project) {
    return { 'success': false, 'msg': '该项目编码已存在，请勿重复创建' };
  }

  project = new Project({
    projectName,
    projectId: code,
    address: location,
    sequence,
    operator,
    len,
    total,
    innerRadius,
    outerRadius,
    geology,
  });

  await project.save();
  return { 'success': true, 'msg': '项目创建成功' };
};

// 更新项目信息
outer.updateProject = async(option) => {
  const { code } = option;
  let project = await Project.findOne({ projectId: code });
  if(!project) {
    // return { 'success': false, 'msg': '项目信息不存在' };
    project = new Project();
  }

  for(const key in option) {
    if(key === 'code') {
      project.projectId = option[key];
    }else if(key ===' location') {
      project.address = option[key];
    } else {
      project[key] = option[key];
    }
  }
  await project.save();

  return { 'success': true, 'msg': '项目信息更新成功' };
};


// 删除项目信息
outer.deleteProject = async (projectId) => {
  try {
    await Project.deleteMany({ projectId });
    return { 'success': true, msg: '项目信息删除成功' };
  } catch (error) {
    return { 'success': false, msg: '项目信息删除失败' };
  }
};

// 获取直播地址
outer.getLiveAddress = async(options) => {
  const { accessToken, deviceSerial, protocol = 1 } = options;
  const url = `https://open.ys7.com/api/lapp/v2/live/address/get?accessToken=${accessToken}&deviceSerial=${deviceSerial}&protocol=${protocol}`;

  const data = await superagent.post(url);
  return data;
};

module.exports = outer;